<?

include "../config/constants.php";
include "../config/EncOpt.php";

if( $_GET[_test]){
	$_POST[XML] = file_get_contents(TEST_CRSS);
	$_POST[CPID] = TEST_CPID;
	$_POST[FEED] = TEST_FEED;
}

if( !$_POST[XML] ){
	echo "ERROR";
	exit;
}

try{

mysql_connect("localhost", "canss", "1022") or die("ERROR: Could not connect " . mysql_error());
mysql_select_db("rule_db");

$RID = md5( $_POST[CPID].$_POST[FEED] );

$query = "SELECT `encType` FROM `rule` WHERE `rid` = '$RID' AND `encType`>0";
$result = mysql_query($query);

if( !$result ){
    echo "ERROR : could not query";
    exit;
}

if( $row = mysql_fetch_row($result) ){
    $encType = $row[0];
}
else{
    echo "ERROR : Rule doesn't exist $RID";
    exit;
}

sscanf($encType, "%d", $E);
$CPID = $_POST[CPID];
$_POST[XML] = stripslashes($_POST[XML]);

$req = new HttpRequest(FORMATTER_URL, HttpRequest::METH_POST);
$req->addPostFields(array('XML'=>$_POST[XML]));
$req->addPostFields(array('CPID'=>$_POST[CPID]));
$Body = $req->send()->getBody();

$xml = new DOMDocument;
$xml->loadXML(stripslashes($Body));


$mysqli = mysqli_connect("localhost", "canss", "1022", "contentsmetadata_db") or die("Could not connect: " . mysql_error());
mysqli_query($mysqli, "SET NAMES 'utf8'");
$wsclient = new SoapClient(WS_PORTAL);

$queries = $xml->getElementsByTagName('query');

foreach( $queries as $query ){
	$query = $query->nodeValue;

	//parse media location
	$l_query = strtolower($query);
	$m_pos1 = strpos($l_query, "<dcindent>");
	$m_pos2 = strpos($l_query, "</dcindent>");
	$medialink = "";//init
	if($m_pos1>=0 && $m_pos2>=0 && $m_pos1 < $m_pos2 )
	{
		$medialink = trim(substr($query, $m_pos1+strlen("<dcindent>"), $m_pos2-($m_pos1+strlen("<dcindent>"))));
		if($medialink && strlen($medialink)>0 && !strpos($medialink, "/"))
			$medialink = "http://webiptv.kaist.ac.kr/iptvportal/MediaContents/".$medialink;
	}
	$query = str_replace("<dcindent>", "", $query);
	$query = str_replace("</dcindent>", "", $query);

	//calc cid
	$cid = md5(md5($CPID).md5($query));

	if( $wsclient->getContentStatusByID( array('_cid'=>$cid) )->return != STATUS_CONTENTS_ENC_FAIL ){
		
		if( !$medialink || strlen($medialink)<=0 )
		{
			echo "REFUSED (medialink failed): $cid<br/>";
			continue;
		}
		
		if( $wsclient->checkCID( array('_cid'=>$cid) )->return ){
			if( $wsclient->getContentStatusByID(array('_cid'=>$cid))->return == STATUS_CONTENTS_REUPLOADABLE )
			{//uploadable state -> del content -> reupload
				$req = new HttpRequest(DEL_CONTENT_URL, HttpRequest::METH_POST);
				$req->addPostFields(array('CID'=>$cid));
				$req->addPostFields(array('DELCONTENT'=>1));
				$Body=$req->send()->getBody();
				if( count( $Body ) >= 0 )
				{
					//echo $Body;
				}
			}else
			{
				echo "REFUSED: $cid<br/>";
				continue;
			}
		}
		$response = $wsclient->createCID( array('_cid'=>$cid) )->return;

		if( !$response ){
			echo "ERROR: createCID return false value for $cid<br/>";
			continue;
		}
		$query2 = "
			INSERT INTO  `contentsmetadata_db`.`tblLocation` (
			`index_2` ,
			`tblContent_tblCID_cid` ,
			`locationprotocol` ,
			`location`
			)
			VALUES (
			NULL ,  '$cid',  'UNKNOWN',  ''
			);
		";

		$query3 = "
			UPDATE `contentsmetadata_db`.`tblContent` SET
			`xmpdm_moddate`=NOW() ,
			`canssContentDescription_owner`='$CPID'
			WHERE `tblCID_cid`='$cid'
		";

		$query = str_replace("<tblPID_pid>", $CPID, $query);
		$query = str_replace("<tblCID_cid>", $cid, $query);
		$query = str_replace("<dc_format>", $EncOpt[$E][0], $query);
		$query = str_replace("<xmpdm_videoframesize>", $EncOpt[$E][1], $query);
		$query = str_replace("<canssvideo_audiocodecs>", $EncOpt[$E][2], $query);
		$query = str_replace("<canssvideo_videocodecs>", $EncOpt[$E][3], $query);
	}
	else{
		//when it failed.
 		$query = $query2 = $query3 = "";

		//refuse re-uploading
		echo "REFUSED: $cid<br/>";
		continue;
		/* code for: re-try
		$req = new HttpRequest(DEL_CONTENT_URL, HttpRequest::METH_POST);
		$req->addPostFields(array('CID'=>$cid));
		$req->addPostFields(array('DELCONTENT'=>1));
		$Body=$req->send()->getBody();
		if( count( $Body )>=0 )
		{
			//echo $Body;
		}
		*/
	}

	$wsclient->updatePIDByCID( array('_cid'=>$cid, '_pid'=>$CPID) );

	if( $query )
	{
		$divquery = split(";", $query);
		foreach($divquery as $divquery_each)
		{
			if( $divquery_each && mysqli_query( $mysqli, $divquery_each ) != 1 )
			{
				echo "ERROR : Fail to insert element into MDB".$divquery_each;
				break;	
			}
		}
	}
//	if( $query && mysqli_query( $mysqli, $query ) != 1 ){
//		echo "ERROR : Fail to insert element into MDB".$query;
//	}	

	if( $query2 && mysqli_query( $mysqli, $query2 ) != 1 ){
		echo "ERROR : Fail to insert element into MDB2".$query2;
	}
	else if( $query3 && mysqli_query( $mysqli, $query3 ) != 1 ){
		echo "ERROR : Fail to insert element into MDB3".$query3;
	}else echo "<content><cid>$cid</cid><link>$medialink</link></content>";
	echo "<br/>";
}

}catch(exception $e){
	echo "FATAL ERROR<br/>$e";
	exit;
}


?>

